<template>
  <div class="app-container">
    <!-- 按钮组 -->
    <el-row>
      <el-col :span="12">
        <el-button type="primary" plain @click="openDrawer">新增</el-button>
        <el-button type="success" plain>高级搜索</el-button>
      </el-col>
      <el-col :span="12">
        <div>
          <el-input placeholder="请输入内容" v-model="searchIpt">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="onSearchClk"
            ></el-button>
          </el-input>
        </div>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table
      :data="list"
      style="width: 100%; margin-top: 20px"
      max-height="330"
    >
      <el-table-column type="index" label="#" width="120"> </el-table-column>
      <el-table-column prop="title" label="题目" width="280"> </el-table-column>
      <el-table-column prop="type" label="分类" width="120"> </el-table-column>
      <el-table-column prop="author" label="作者" width="100">
      </el-table-column>
      <el-table-column prop="created" sortable label="发布时间" width="200">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openDrawer(scope.row)">
            编辑
          </el-button>
          <el-button type="text" size="small" @click="onDetail(scope.row)">
            详情
          </el-button>
          <el-button @click="deleteRow(scope.row.id)" type="text" size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 5, 8, 10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 抽屉 -->
    <el-drawer size="70%" :visible.sync="drawer" direction="rtl" @close="close">
      <el-form :model="form" ref="ruleForm" :rules="rules" label-width="80px">
        <el-form-item label="题目" prop="title">
          <el-input
            v-model="form.title"
            placeholder="测试题目"
            :disabled="isDetail"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="cid">
          <el-select
            v-model="form.cid"
            :disabled="isDetail"
            placeholder="请选择类别"
          >
            <template v-for="(v, i) in classifyList">
              <el-option
                :key="i"
                v-if="v.id"
                :label="v.name"
                :value="v.id"
              ></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="选项" prop="options">
          <el-row class="display-flex">
            <!-- 选项 答案 -->
            <el-col :span="20">
              <el-row v-for="(v, i) in form.options" :key="i">
                <el-col :span="2">
                  <el-checkbox
                    v-model="v.checked"
                    :disabled="isDetail"
                    :label="v.index"
                    name="prop"
                  ></el-checkbox>
                </el-col>
                <el-col :span="22">
                  <el-input
                    type="textarea"
                    :disabled="isDetail"
                    autosize
                    v-model="v.value"
                  >
                  </el-input>
                </el-col>
              </el-row>
            </el-col>
            <!-- + - 按钮 -->
            <el-col :span="4" class="circle-btn">
              <div>
                <el-button
                  type="success"
                  icon="el-icon-plus"
                  circle
                  @click="addChoice"
                  :disabled="isDetail"
                >
                </el-button>
                <el-button
                  v-if="form.options.length > 4"
                  type="danger"
                  icon="el-icon-minus"
                  circle
                  @click="reduceChoice"
                  :disabled="isDetail"
                >
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="答案">
          {{ form.answers }}
        </el-form-item>
        <el-form-item label="答案提示" prop="tips">
          <el-input
            v-model="form.tips"
            :disabled="isDetail"
            placeholder="答案提示"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit('ruleForm')"
            v-if="!isDetail"
          >
            {{ title }}
          </el-button>
          <el-button @click="cancelClk">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations, mapGetters } from "vuex";
export default {
  data() {
    return {
      drawer: false,
      isDetail: false,
      searchIpt: "",
      title: "新增",
      form: {
        answers: [],
        options: [
          {
            index: "A",
          },
          {
            index: "B",
          },
          {
            index: "C",
          },
          {
            index: "D",
          },
        ],
      },
      rules: {
        title: [
          { required: true, message: "请输入题目", trigger: "blur" },
          {
            min: 3,
            max: 100,
            message: "长度在 3 到 100 个字符",
            trigger: "blur",
          },
        ],
        cid: [{ required: true, message: "请选择类别", trigger: "change" }],
        options: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个活动性质",
            trigger: "change",
          },
        ],
        tips: [
          { required: true, message: "请输入答案提示", trigger: "blur" },
          {
            min: 3,
            max: 100,
            message: "长度在 3 到 100 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapActions("exam", ["getlist", "addlist", "updatelist", "dellist"]),
    ...mapMutations("exam", [
      "SET_PAGESIZE",
      "SET_CURRENTPAGE",
      "SET_SEARCHVAL",
    ]),
    // 搜索
    async onSearchClk() {
      if (this.searchIpt.trim() == "") {
        this.$message("请输入您要搜索的内容!!!");
        return;
      }

      await this.SET_SEARCHVAL(this.searchIpt.trim());
      this.getlist();
    },
    // 查看详情
    onDetail(row) {
      this.form = { ...row };
      this.isDetail = true;
      this.drawer = true;
    },
    // 单删
    deleteRow(id) {
      this.$confirm("此操作将永久删除该条信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.dellist(id);

          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getlist();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击确定 新增 || 修改
    onSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 处理form表单的选项
          // 选项内容为空
          await this.form.options.map((v) => {
            if (!v.value) {
              this.$message(`请完成${v.index}的选项答案!!!`);
              return;
            }
          });
          // 未选
          let hasChecked = !!this.form.options.filter((v) => v.checked).length;
          if (!hasChecked) {
            this.$message("请选择正确答案!!!");
            return;
          }

          let obj = { ...this.form };
          obj.answers = JSON.stringify(obj.answers);
          obj.options = JSON.stringify(obj.options);
          obj.uid = this.$store.getters.uid;

          if (this.form.id) {
            // 修改
            await this.updatelist(obj);
          } else {
            // 新增
            await this.addlist(obj);
          }
          this.cancelClk();
          this.getlist();
        } else {
          this.$message("error submit!!");
          return false;
        }
      });
    },
    // 取消
    cancelClk() {
      this.form = {
        answers: [],
        options: [
          {
            index: "A",
          },
          {
            index: "B",
          },
          {
            index: "C",
          },
          {
            index: "D",
          },
        ],
      };
      this.isDetail = false;
      this.drawer = false;
    },
    // 打开抽屉
    openDrawer(row) {
      // console.log(row);
      this.isDetail = false;
      if (row.id) {
        //修改
        this.form = { ...row };
        this.title = "修改";
      } else {
        this.title = "新增";
      }
      this.drawer = true;
    },
    // 加
    addChoice() {
      let index = String.fromCharCode(this.form.options.length + 65);
      this.form.options.push({ index });
    },
    // 减
    reduceChoice() {
      this.form.options.pop();
      // this.form.options.splice(this.form.options.length - 1, 1);
    },
    handleSizeChange(val) {
      this.SET_PAGESIZE(val);
      this.getlist();
    },
    handleCurrentChange(val) {
      this.SET_CURRENTPAGE(val);
      this.getlist();
    },
    close() {
      this.form = {
        answers: [],
        options: [
          {
            index: "A",
          },
          {
            index: "B",
          },
          {
            index: "C",
          },
          {
            index: "D",
          },
        ],
      };
      // console.log(this.form);
    },
  },
  computed: {
    ...mapState("exam", ["list", "total", "currentPage", "pageSize"]),
    ...mapState("classify", ["classifyList"]),
  },
  async mounted() {
    await this.getlist();
    await this.$store.dispatch("classify/getCid");
  },
  watch: {
    "form.options": {
      deep: true,
      handler(val) {
        let answersArr = [];
        val.map((v) => {
          if (v.checked) {
            answersArr.push(v.index);
          }
        });
        this.form.answers = answersArr;
      },
    },
  },
};
</script>

<style scoped>
</style>

<style>
.display-flex {
  display: flex;
}

.circle-btn {
  align-self: flex-end;
  margin-left: 15px;
}
</style>